import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { View, Text, SafeAreaView, Image, TouchableOpacity, ScrollView, Dimensions, Modal } from 'react-native';
import { DatePicker } from '@ant-design/react-native';
import { PieChart } from 'react-native-chart-kit';
import { styles } from './styles';
import { getUserScoreApi, getWorkRecordsApi } from './api';

interface PersonalCenterProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
}

interface UserInfo {
    user_img?: string;
    user_num?: string;
    user_name?: string;
    user_rank?: number;
    work_hour?: string;
    work_quantity?: number;
}

interface WorkRecord {
    id: string;
    create_time: string;
    update_time: string;
    tenant_id: string;
    delete_flag: boolean;
    task_id: string;
    user_id: string;
    user_name: string;
    wip_num: string;
    work_order_id: string;
    batch_order_id: string;
    batch_order_num: string;
    work_order_num: string;
    order_priority: number;
    product_id: string;
    product_type_vv: number;
    product_type_kk: string;
    product_short_name: string;
    product_name: string;
    product_model: string;
    product_specs: string;
    product_encode: string;
    product_link: string | null;
    mbom_id: string;
    mbom_num: string;
    mbom_sort: number;
    sku_id: string;
    sku: string;
    process_id: string;
    process_num: string;
    process_name: string;
    capacity: number;
    work_quantity: number;
    self_unqualified_quantity: number;
    qc_unqualified_quantity: number;
    self_fatal_quantity: number;
    qc_fatal_quantity: number;
    self_rework_quantity: number;
    qc_rework_quantity: number;
    self_accept_quantity: number;
    qc_accept_quantity: number;
    group_id: string;
    station_id: string;
    station_num: string;
    line_id: string | null;
    line_num: string | null;
    device_id: string;
    device_num: string;
    standard_time: number;
    produce_start: string;
    produce_end: string;
    produce_time: number;
    is_reach: boolean;
    first_end: number;
    inspect_state: boolean;
    state: number;
    tester_user_id: string | null;
    tester_user_name: string | null;
    room_id: string;
    room_name: string;
    yield: number;
    work_day: string;
    work_month: string;
    work_year: string;
    work_week: string;
}

const PersonalCenter: React.FC<PersonalCenterProps> = ({ onNavigateToLogin: _onNavigateToLogin, onBackPress }) => {
    const [selectedDate, setSelectedDate] = useState<Date>(new Date(2025, 7, 1)); // 默认2025-08
    const [userScore, setUserScore] = useState<any>(null);
    const [_loading, setLoading] = useState(false);

    // 工作记录相关状态
    const [workRecords, setWorkRecords] = useState<WorkRecord[]>([]);
    const [workRecordsLoading, setWorkRecordsLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        size: 10,
        total: 0
    });

    // 图片预览相关状态
    const [showImageModal, setShowImageModal] = useState(false);
    const [previewImageUrl, setPreviewImageUrl] = useState('');

    // 获取用户积分
    const fetchUserScore = useCallback(async (workMonth: string) => {
        try {
            setLoading(true);
            const response = await getUserScoreApi(workMonth);
            setUserScore(response);
            console.log('个人中心数据:', response);
        } catch (error) {
            console.error('个人中心数据获取失败:', error);
        } finally {
            setLoading(false);
        }
    }, []);

    // 获取工作记录
    const fetchWorkRecords = useCallback(async (workMonth: string, current: number = 1) => {
        try {
            setWorkRecordsLoading(true);
            const params = {
                work_month: workMonth,
                size: pagination.size,
                current: current
            };
            const response = await getWorkRecordsApi(params);
            console.log('工作记录数据:', response);

            if (response && response.data) {
                setWorkRecords(response.data.records || []);
                setPagination(prev => ({
                    ...prev,
                    current: current,
                    total: response.data.total || 0
                }));
            }
        } catch (error) {
            console.error('工作记录获取失败:', error);
            // 如果接口失败，清空数据
            setWorkRecords([]);
            setPagination(prev => ({
                ...prev,
                current: current,
                total: 0
            }));
        } finally {
            setWorkRecordsLoading(false);
        }
    }, [pagination.size]); // Removed mockWorkRecords from dependency array

    // 处理日期变化
    const handleDateChange = (date: Date) => {
        if (date) {
            setSelectedDate(date);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const workMonth = `${year}-${month}`;
            fetchUserScore(workMonth);
            // 重置分页并获取工作记录
            setPagination(prev => ({ ...prev, current: 1 }));
            fetchWorkRecords(workMonth, 1);
        }
    };

    // 处理分页变化
    const handlePageChange = (page: number) => {
        const year = selectedDate.getFullYear();
        const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
        const workMonth = `${year}-${month}`;
        fetchWorkRecords(workMonth, page);
    };

    // 格式化日期显示
    const formatDateDisplay = (date: Date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        return `${year}-${month}`;
    };

    // 组件挂载时获取默认月份的数据
    useEffect(() => {
        fetchUserScore('2025-08');
        fetchWorkRecords('2025-08', 1);
    }, [fetchUserScore, fetchWorkRecords]);

    const handleBackPress = () => {
        console.log('返回按钮被点击');
        if (onBackPress) {
            onBackPress();
        }
    };

    // 处理图片预览
    const handlePreviewImage = (imageUrl: string | null) => {
        if (imageUrl) {
            setPreviewImageUrl(imageUrl);
        } else {
            // 如果没有图片，使用默认图片
            setPreviewImageUrl('../../../../assets/zwtp.png');
        }
        setShowImageModal(true);
    };

    // 关闭图片预览
    const handleCloseImageModal = () => {
        setShowImageModal(false);
        setPreviewImageUrl('');
    };

    // 渲染分页组件
    const renderPagination = () => {
        const totalPages = Math.ceil(pagination.total / pagination.size);
        if (totalPages <= 1) return null;

        const pages = [];
        const currentPage = pagination.current;

        // 显示页码按钮
        for (let i = 1; i <= totalPages; i++) {
            if (
                i === 1 || // 第一页
                i === totalPages || // 最后一页
                (i >= currentPage - 1 && i <= currentPage + 1) // 当前页附近的页码
            ) {
                pages.push(
                    <TouchableOpacity
                        key={i}
                        style={[
                            styles.pageButton,
                            i === currentPage && styles.pageButtonActive
                        ]}
                        onPress={() => handlePageChange(i)}
                    >
                        <Text style={[
                            styles.pageButtonText,
                            i === currentPage && styles.pageButtonTextActive
                        ]}>
                            {i}
                        </Text>
                    </TouchableOpacity>
                );
            } else if (i === currentPage - 2 || i === currentPage + 2) {
                pages.push(
                    <Text key={i} style={styles.pageEllipsis}>...</Text>
                );
            }
        }

        return (
            <View style={styles.paginationContainer}>
                <TouchableOpacity
                    style={[
                        styles.pageButton,
                        currentPage === 1 && styles.pageButtonDisabled
                    ]}
                    onPress={() => currentPage > 1 && handlePageChange(currentPage - 1)}
                    disabled={currentPage === 1}
                >
                    <Text style={[
                        styles.pageButtonText,
                        currentPage === 1 && styles.pageButtonTextDisabled
                    ]}>
                        上一页
                    </Text>
                </TouchableOpacity>

                {pages}

                <TouchableOpacity
                    style={[
                        styles.pageButton,
                        currentPage === totalPages && styles.pageButtonDisabled
                    ]}
                    onPress={() => currentPage < totalPages && handlePageChange(currentPage + 1)}
                    disabled={currentPage === totalPages}
                >
                    <Text style={[
                        styles.pageButtonText,
                        currentPage === totalPages && styles.pageButtonTextDisabled
                    ]}>
                        下一页
                    </Text>
                </TouchableOpacity>

                {/* 显示总条数信息 */}
                <Text style={styles.totalInfoText}>共 {pagination.total} 条</Text>
            </View>
        );
    };

    // 渲染工作记录表格
    const renderWorkRecordsTable = () => {
        return (
            <View style={styles.tableContainer}>
                <View style={styles.tableHeader}>
                    <Text style={styles.tableHeaderCell}>工单号</Text>
                    <Text style={styles.tableHeaderCell}>产品</Text>
                    <Text style={styles.tableHeaderCell}>规格</Text>
                    <Text style={styles.tableHeaderCell}>型号</Text>
                    <Text style={styles.tableHeaderCell}>图片</Text>
                    <Text style={styles.tableHeaderCell}>设备号</Text>
                    <Text style={styles.tableHeaderCell}>工位号</Text>
                    <Text style={styles.tableHeaderCell}>工作时间</Text>
                    <Text style={styles.tableHeaderCell}>数量</Text>
                    <Text style={styles.tableHeaderCell}>报废数</Text>
                    <Text style={styles.tableHeaderCell}>计划开始时间</Text>
                    <Text style={styles.tableHeaderCellLast}>计划结束时间</Text>
                </View>
                <ScrollView style={styles.tableBody}>
                    {workRecordsLoading ? (
                        <View style={styles.loadingContainer}>
                            <Text style={styles.loadingText}>加载中...</Text>
                        </View>
                    ) : workRecords.length === 0 ? (
                        <View style={styles.noDataContainer}>
                            <Text style={styles.noDataText}>暂无数据</Text>
                        </View>
                    ) : (
                        workRecords.map((item, index) => (
                            <View key={item.id || index} style={styles.tableRow}>
                                <Text style={styles.tableCell}>{item.work_order_num || '-'}</Text>
                                <Text style={styles.tableCell}>{item.product_short_name || '-'}</Text>
                                <Text style={styles.tableCell}>{item.product_specs || '-'}</Text>
                                <Text style={styles.tableCell}>{item.product_model || '-'}</Text>
                                <TouchableOpacity
                                    style={styles.tableCell}
                                    onPress={() => handlePreviewImage(item.product_link)}
                                >
                                    <Text style={{ color: '#1890ff', fontSize: 12 }}>查看图片</Text>
                                </TouchableOpacity>
                                <Text style={styles.tableCell}>{item.device_num || '-'}</Text>
                                <Text style={styles.tableCell}>{item.station_num || '-'}</Text>
                                <Text style={styles.tableCell}>{item.produce_time || 0}</Text>
                                <Text style={styles.tableCell}>{item.work_quantity || 0}</Text>
                                <Text style={styles.tableCell}>{item.qc_unqualified_quantity || 0}</Text>
                                <Text style={styles.tableCell}>{item.produce_start || '-'}</Text>
                                <Text style={styles.tableCellLast}>{item.produce_end || '-'}</Text>
                            </View>
                        ))
                    )}
                </ScrollView>

                {/* 分页组件 */}
                {renderPagination()}
            </View>
        );
    };

    // 渲染工作成果趋势图表
    const renderWorkTrendChart = () => {
        // 从API数据中提取趋势数据
        const trendData = userScore?.data?.work_result_trend || [];

        // 处理数据，提取日期、工作时长和报工数量
        const chartData = trendData.map((item: any, index: number) => ({
            date: item.work_day ? item.work_day.split('-')[2] : `${index + 1}`.padStart(2, '0'), // 提取日期
            workHours: item.produce_time || 0, // 工作时长 - 使用produce_time字段
            workQuantity: item.work_quantity || 0 // 报工数量 - 使用work_quantity字段
        }));

        // 计算最大值用于缩放
        const maxWorkHours = Math.max(...chartData.map((item: any) => item.workHours), 1);
        const maxWorkQuantity = Math.max(...chartData.map((item: any) => item.workQuantity), 1);

        // 调试信息
        console.log('图表数据:', chartData);
        console.log('最大工作时长:', maxWorkHours);
        console.log('最大报工数量:', maxWorkQuantity);

        return (
            <View style={styles.cardContent}>
                {/* 图例区域 */}
                <View style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', marginBottom: 0, marginTop: 40 }}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', marginRight: 16 }}>
                        <View style={{ width: 8, height: 8, backgroundColor: "#1890ff", marginRight: 4, borderRadius: 2 }} />
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#333' }]}>工作时长</Text>
                    </View>
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <View style={{ width: 8, height: 8, backgroundColor: "#ff4d4f", marginRight: 4, borderRadius: 4 }} />
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#333' }]}>报工数量</Text>
                    </View>
                </View>

                {/* 图表区域 */}
                <View style={{ height: 200, width: '100%', position: 'relative', paddingHorizontal: 20, marginTop: 10 }}>
                    {/* 左Y轴 - 工作时长 */}
                    <View style={{ position: 'absolute', left: 0, top: 10, height: 140, justifyContent: 'space-between', alignItems: 'flex-end' }}>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>{maxWorkHours}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>{Math.round(maxWorkHours * 0.75)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>{Math.round(maxWorkHours * 0.5)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>{Math.round(maxWorkHours * 0.25)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>0</Text>
                    </View>

                    {/* 右Y轴 - 报工数量 */}
                    <View style={{ position: 'absolute', right: 0, top: 10, height: 140, justifyContent: 'space-between', alignItems: 'flex-start' }}>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>{maxWorkQuantity}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>{Math.round(maxWorkQuantity * 0.75)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>{Math.round(maxWorkQuantity * 0.5)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>{Math.round(maxWorkQuantity * 0.25)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>0</Text>
                    </View>

                    {/* 网格线 */}
                    <View style={{ position: 'absolute', left: 25, right: 25, top: 10, height: 140 }}>
                        {[0, 1, 2, 3, 4].map((line) => (
                            <View key={line} style={{
                                position: 'absolute',
                                left: 0,
                                right: 0,
                                top: (line / 4) * 140,
                                height: 1,
                                backgroundColor: '#f0f0f0'
                            }} />
                        ))}
                    </View>

                    {/* 数据点和连线 */}
                    <View style={{ flexDirection: 'row', alignItems: 'flex-end', height: 140, marginLeft: 25, marginRight: 25, marginBottom: 40, marginTop: 10 }}>
                        {chartData.slice(0, 7).map((item: any, index: number) => (
                            <View key={index} style={{ alignItems: 'center', flex: 1, position: 'relative' }}>
                                {/* 柱状图 - 工作时长（从下到上，正确对齐到左Y轴） */}
                                <View
                                    style={{
                                        width: 12,
                                        height: Math.max((item.workHours / maxWorkHours) * 140, 2),
                                        backgroundColor: "#1890ff",
                                        borderRadius: 1,
                                        position: 'absolute',
                                        bottom: 0
                                    }}
                                />

                                {/* 折线图点 - 报工数量（正确对齐到右Y轴） */}
                                <View
                                    style={{
                                        width: 6,
                                        height: 6,
                                        backgroundColor: "#ff4d4f",
                                        borderRadius: 3,
                                        position: 'absolute',
                                        bottom: Math.max((item.workQuantity / maxWorkQuantity) * 140, 2)
                                    }}
                                />



                                {/* X轴标签 - 移到图表下方 */}
                                <Text style={[styles.cardPlaceholder, {
                                    fontSize: 9,
                                    textAlign: 'center',
                                    color: '#666',
                                    position: 'absolute',
                                    bottom: -20,
                                    left: '50%',
                                    transform: [{ translateX: -7 }]
                                }]}>{item.date}</Text>
                            </View>
                        ))}
                    </View>
                </View>
            </View>
        );
    };

    // 渲染工作成果统计图表
    const renderWorkAchievementChart = () => {
        // 使用真实的API数据
        const workStats = {
            scrapCount: userScore?.data?.fatal_quantity || 0,      // 报废数
            workCount: userScore?.data?.work_quantity || 0,        // 合工数量
            concessionCount: userScore?.data?.accept_quantity || 0 // 让步接收数
        };

        const chartData = [
            { name: "报废数", y: workStats.scrapCount, color: "#1890ff", legendFontColor: "#333", legendFontSize: 12 },
            { name: "合工数量", y: workStats.workCount, color: "#52c41a", legendFontColor: "#333", legendFontSize: 12 },
            { name: "让步接收数", y: workStats.concessionCount, color: "#fa8c16", legendFontColor: "#333", legendFontSize: 12 }
        ];

        return (
            <View style={styles.cardContent}>
                {/* 图表区域 */}
                <View style={[styles.cardContent, { alignItems: 'center', justifyContent: 'center', height: 150, width: '100%' }]}>
                    <PieChart
                        data={chartData}
                        width={120}
                        height={120}
                        chartConfig={{
                            backgroundColor: "#fff",
                            backgroundGradientFrom: "#fff",
                            backgroundGradientTo: "#fff",
                            decimalPlaces: 0,
                            color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
                            style: {
                                borderRadius: 16,
                            },
                        }}
                        accessor="y"
                        backgroundColor="transparent"
                        paddingLeft="24"
                        absolute
                        hasLegend={false}
                    />
                </View>

                {/* 图例区域 - 显示在图表下方 */}
                <View style={[styles.cardContent, { marginTop: 16, alignItems: 'center' }]}>
                    <View style={[styles.cardContent, { alignItems: 'center' }]}>
                        <View style={[styles.cardContent, { flexDirection: 'row', alignItems: 'center', marginBottom: 8 }]}>
                            <View style={[styles.cardContent, { width: 8, height: 8, backgroundColor: "#1890ff", marginRight: 4, borderRadius: 1 }]} />
                            <Text style={[styles.cardPlaceholder, { fontSize: 10 }]}>报废数 {workStats.scrapCount}个</Text>
                        </View>
                        <View style={[styles.cardContent, { flexDirection: 'row', alignItems: 'center', marginBottom: 8 }]}>
                            <View style={[styles.cardContent, { width: 8, height: 8, backgroundColor: "#52c41a", marginRight: 4, borderRadius: 1 }]} />
                            <Text style={[styles.cardPlaceholder, { fontSize: 10 }]}>合工数量 {workStats.workCount}个</Text>
                        </View>
                        <View style={[styles.cardContent, { flexDirection: 'row', alignItems: 'center' }]}>
                            <View style={[styles.cardContent, { width: 8, height: 8, backgroundColor: "#fa8c16", marginRight: 4, borderRadius: 1 }]} />
                            <Text style={[styles.cardPlaceholder, { fontSize: 10 }]}>让步接收数 {workStats.concessionCount}个</Text>
                        </View>
                    </View>
                </View>
            </View>
        );
    };
    // 渲染工作绩效趋势图表
    const renderWorkPerformanceTrendChart = () => {
        // 从API数据中提取趋势数据
        const trendData = userScore?.data?.rank_list || [];

        // 处理数据，提取日期、工作时长和报工数量
        const chartData = trendData.map((item: any, index: number) => ({
            date: item.work_day ? item.work_day.split('-')[2] : `${index + 1}`.padStart(2, '0'), // 提取日期
            workHours: item.hours || 0, // 工作时长 - 使用hours字段
            workQuantity: item.work_quantity || 0 // 报工数量 - 使用work_quantity字段
        }));

        // 计算最大值用于缩放
        const maxWorkHours = Math.max(...chartData.map((item: any) => item.workHours), 1);
        const maxWorkQuantity = Math.max(...chartData.map((item: any) => item.workQuantity), 1);

        // 调试信息
        console.log('图表数据:', chartData);
        console.log('最大工作时长:', maxWorkHours);
        console.log('最大报工数量:', maxWorkQuantity);

        return (
            <View style={styles.cardContent}>
                {/* 图例区域 */}
                <View style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', marginBottom: 0, marginTop: 40 }}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', marginRight: 16 }}>
                        <View style={{ width: 8, height: 8, backgroundColor: "#1890ff", marginRight: 4, borderRadius: 2 }} />
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#333' }]}>工作时长</Text>
                    </View>
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <View style={{ width: 8, height: 8, backgroundColor: "#ff4d4f", marginRight: 4, borderRadius: 4 }} />
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#333' }]}>报工数量</Text>
                    </View>
                </View>

                {/* 图表区域 */}
                <View style={{ height: 200, width: '100%', position: 'relative', paddingHorizontal: 20, marginTop: 10 }}>
                    {/* 左Y轴 - 工作时长 */}
                    <View style={{ position: 'absolute', left: 0, top: 10, height: 140, justifyContent: 'space-between', alignItems: 'flex-end' }}>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>{maxWorkHours}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>{Math.round(maxWorkHours * 0.75)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>{Math.round(maxWorkHours * 0.5)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>{Math.round(maxWorkHours * 0.25)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#1890ff' }]}>0</Text>
                    </View>

                    {/* 右Y轴 - 报工数量 */}
                    <View style={{ position: 'absolute', right: 0, top: 10, height: 140, justifyContent: 'space-between', alignItems: 'flex-start' }}>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>{maxWorkQuantity}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>{Math.round(maxWorkQuantity * 0.75)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>{Math.round(maxWorkQuantity * 0.5)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>{Math.round(maxWorkQuantity * 0.25)}</Text>
                        <Text style={[styles.cardPlaceholder, { fontSize: 10, color: '#ff4d4f' }]}>0</Text>
                    </View>

                    {/* 网格线 */}
                    <View style={{ position: 'absolute', left: 25, right: 25, top: 10, height: 140 }}>
                        {[0, 1, 2, 3, 4].map((line) => (
                            <View key={line} style={{
                                position: 'absolute',
                                left: 0,
                                right: 0,
                                top: (line / 4) * 140,
                                height: 1,
                                backgroundColor: '#f0f0f0'
                            }} />
                        ))}
                    </View>

                    {/* 数据点和连线 */}
                    <View style={{ flexDirection: 'row', alignItems: 'flex-end', height: 140, marginLeft: 25, marginRight: 25, marginBottom: 40, marginTop: 10 }}>
                        {chartData.slice(0, 7).map((item: any, index: number) => (
                            <View key={index} style={{ alignItems: 'center', flex: 1, position: 'relative' }}>
                                {/* 柱状图 - 工作时长（从下到上，正确对齐到左Y轴） */}
                                <View
                                    style={{
                                        width: 12,
                                        height: Math.max((item.workHours / maxWorkHours) * 140, 2),
                                        backgroundColor: "#1890ff",
                                        borderRadius: 1,
                                        position: 'absolute',
                                        bottom: 0
                                    }}
                                />

                                {/* 折线图点 - 报工数量（正确对齐到右Y轴） */}
                                <View
                                    style={{
                                        width: 6,
                                        height: 6,
                                        backgroundColor: "#ff4d4f",
                                        borderRadius: 3,
                                        position: 'absolute',
                                        bottom: Math.max((item.workQuantity / maxWorkQuantity) * 140, 2)
                                    }}
                                />



                                {/* X轴标签 - 移到图表下方 */}
                                <Text style={[styles.cardPlaceholder, {
                                    fontSize: 9,
                                    textAlign: 'center',
                                    color: '#666',
                                    position: 'absolute',
                                    bottom: -20,
                                    left: '50%',
                                    transform: [{ translateX: -7 }]
                                }]}>{item.date}</Text>
                            </View>
                        ))}
                    </View>
                </View>
            </View>
        );
    };

    // 渲染图片预览模态框
    const renderImageModal = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={showImageModal}
                onRequestClose={handleCloseImageModal}
            >
                <View style={{
                    flex: 1,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    justifyContent: 'center',
                    alignItems: 'center'
                }}>
                    <TouchableOpacity
                        style={{
                            flex: 1,
                            justifyContent: 'center',
                            alignItems: 'center',
                            width: '100%'
                        }}
                        onPress={handleCloseImageModal}
                        activeOpacity={1}
                    >
                        <Image
                            source={
                                previewImageUrl.startsWith('http') || previewImageUrl.startsWith('file://')
                                    ? { uri: previewImageUrl }
                                    : require('../../../../assets/zwtp.png')
                            }
                            style={{
                                width: '80%',
                                height: '60%',
                                resizeMode: 'contain'
                            }}
                        />
                        <TouchableOpacity
                            style={{
                                position: 'absolute',
                                top: 50,
                                right: 20,
                                width: 40,
                                height: 40,
                                backgroundColor: 'rgba(255, 255, 255, 0.8)',
                                borderRadius: 20,
                                justifyContent: 'center',
                                alignItems: 'center'
                            }}
                            onPress={handleCloseImageModal}
                        >
                            <Text style={{ fontSize: 24, color: '#333' }}>×</Text>
                        </TouchableOpacity>
                    </TouchableOpacity>
                </View>
            </Modal>
        );
    };

    // 渲染用户信息卡片
    const renderUserInfoCard = () => {
        if (!userScore || !userScore.data) {
            return (
                <View style={styles.cardContent}>
                    <Text style={styles.cardPlaceholder}>加载中...</Text>
                </View>
            );
        }

        const userInfo: UserInfo = userScore.data;

        return (
            <View style={styles.cardContent}>
                <View style={styles.userAvatarContainer}>
                    <Image
                        source={
                            userInfo.user_img
                                ? { uri: userInfo.user_img }
                                : require('../../../../assets/mrtx.png')
                        }
                        style={styles.userAvatar}
                        resizeMode="cover"
                    />
                </View>
                <View style={styles.userInfoContainer}>
                    <Text style={styles.userInfoLabel}>工号：{userInfo.user_num || '-'}</Text>
                    <Text style={styles.userInfoLabel}>姓名：{userInfo.user_name || '-'}</Text>
                    <Text style={styles.userInfoLabel}>
                        绩效排名：{userInfo.user_rank ? `第${userInfo.user_rank}名` : '-'}
                    </Text>
                    <Text style={styles.userInfoLabel}>
                        已报工工时：{userInfo.work_hour || '0'} 小时
                    </Text>
                    <Text style={styles.userInfoLabel}>
                        已报工数量：{userInfo.work_quantity || 0} 件
                    </Text>
                </View>
            </View>
        );
    };

    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.header}>
                <Image
                    source={require('../../../../assets/terminal/home-header.png')}
                    style={styles.headerBackground}
                    resizeMode="cover"
                />
                <View style={styles.headerContent}>
                    {/* <Image
                        source={require('../../../../assets/terminal/home-logo.png')}
                        style={styles.logo}
                        resizeMode="contain"
                    /> */}
                    <Text style={styles.headerText}>MES终端服务系统</Text>
                </View>
                <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
                    <Image source={require('../../../../assets/fanhui.png')} style={styles.backIcon} />
                </TouchableOpacity>
            </View>

            <View style={styles.content}>
                <View style={styles.datePickerContainer}>
                    <Text style={styles.datePickerLabel}>选择月份：</Text>
                    <DatePicker
                        value={selectedDate}
                        mode="date"
                        precision="month"
                        minDate={new Date(2020, 0, 1)}
                        maxDate={new Date(2030, 11, 31)}
                        onChange={handleDateChange}
                        format="YYYY-MM"
                    >
                        <TouchableOpacity style={styles.dateSelector}>
                            <Text style={styles.dateText}>{formatDateDisplay(selectedDate)}</Text>
                            {/* <Image source={require('../../../../assets/xiala.png')} style={styles.arrowIcon} /> */}
                        </TouchableOpacity>
                    </DatePicker>
                </View>

                {/* 4个数据概览卡片 */}
                <View style={styles.cardsContainer}>
                    <View style={styles.cardRow}>
                        <View style={styles.card}>
                            <View style={styles.cardContent}>
                                {renderWorkAchievementChart()}
                            </View>
                        </View>
                        {/* 第二个卡片 - 工作成果趋势 */}
                        <View style={styles.card}>
                            <Text style={[styles.cardTitle, { textAlign: 'left', marginTop: -8 }]}>工作成果趋势</Text>
                            {renderWorkTrendChart()}
                        </View>
                        <View style={styles.card}>
                            <Text style={[styles.cardTitle, { textAlign: 'left', marginTop: -8 }]}>工作绩效趋势</Text>
                            {renderWorkPerformanceTrendChart()}
                        </View>
                        <View style={styles.card}>
                            {renderUserInfoCard()}
                        </View>
                    </View>
                </View>

                {/* 工作记录表格 */}
                <View style={styles.workRecordsContainer}>
                    <Text style={styles.workRecordsTitle}>工作记录</Text>
                    {renderWorkRecordsTable()}
                </View>
            </View>

            {/* 图片预览模态框 */}
            {renderImageModal()}
        </SafeAreaView>
    );
};

export default PersonalCenter;